import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from '../views/user/Register.vue'
import UserEdit from '../views/user/UserEdit.vue'
import Demo from '../views/user/Demo.vue'
Vue.use(VueRouter)
// 全局的把push的异常给处理了
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/', name: 'index', component: () => import('../views/news/Index.vue')
  },
  {
    path: '/search', name: 'search', component: () => import('../views/news/Search.vue')
  },
  {
    path: '/manage', name: 'manage', component: () => import('../views/news/Manage.vue')
  },
  {
    path: '/post-detail/:id', name: 'post-detail', component: () => import('../views/news/PostDetail.vue')
  },
  {
    path: '/login', name: 'login', component: () => import('../views/user/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: Register

  },
  {
    path: '/user', name: 'user', component: () => import('../views/user/User.vue')
  },
  {
    path: '/user-edit',
    name: 'user-edit',
    component: UserEdit

  },
  {
    path: '/demo',
    name: 'demo',
    component: Demo

  },
  {
    path: '/my-follow', name: 'my-follow', component: () => import('../views/user/MyFollow.vue')
  },
  {
    path: '/my-comment', name: 'my-comment', component: () => import('../views/user/MyComment.vue')
  },
  {
    path: '/my-star', name: 'my-star', component: () => import('../views/user/MyStar.vue')
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach(function(to, from, next) {
  const token = localStorage.getItem('token')
  const authUrls = ['/user', '/user-edit', '/my-follow', '/my-comment', '/my-star']
  if (!authUrls.includes(to.path) || token) {
    next()
  } else {
    router.push('/login').catch(e => {
      console.log(e)
    })
  }
})
// router.afterEach()

export default router
